<!--
 * @Descripttion: 卡券列表
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2021-04-28 16:06:45
-->
<template>
  <div class="lb-red-packit">
    <top-nav />
    <div class="page-main">
      <el-row class="page-top-operate">
        <lb-button
          type="primary"
          icon="el-icon-plus"
          @click="$router.push('/malls/addRedPackit')"
          >{{ $t('menu.AddRedPackit') }}</lb-button
        >
      </el-row>
      <el-row class="page-search-form">
        <el-form
          @submit.native.prevent
          :model="ruleForm"
          ref="ruleForm"
          :inline="true"
        >
          <el-form-item label="标题" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('ruleForm')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </el-row>
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID"> </el-table-column>
        <el-table-column prop="title" label="标题"> </el-table-column>
        <el-table-column prop="type_text" label="类型"> </el-table-column>
        <el-table-column prop="full" label="满">
          <template slot-scope="scope">
            <div v-if="scope.row.use_limit === 1">-</div>
            <div v-else>{{ scope.row.full }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="reduce" label="减">
          <template slot-scope="scope">
            <div v-if="scope.row.coupon_type === 0">{{ scope.row.reduce }}</div>
            <div v-else>-</div>
          </template>
        </el-table-column>
        <el-table-column prop="number" label="每个员工发放数量">
          <template slot-scope="scope">
            <div v-if="scope.row.send_type === 2">不限</div>
            <div v-else>{{ scope.row.number }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="top" label="排序值"> </el-table-column>
        <el-table-column prop="create_time" label="加入时间"> </el-table-column>
        <el-table-column prop="status_text" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="updateOrDelStatus(scope.row.status, scope.row.id)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                type="primary"
                plain
                size="mini"
                @click="confirmIsOperate(scope.row.id)"
                >{{ $t('action.edit') }}</lb-button
              >
              <lb-button
                type="danger"
                plain
                size="mini"
                @click="confirmDel(scope.row.id)"
                >{{ $t('action.delete') }}</lb-button
              >
              <lb-button
                type="success"
                plain
                size="mini"
                @click="openDialogRedPackit(scope.row.id)"
                >下载卡券码</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :batch="false"
        :page="ruleForm.page"
        :pageSize="ruleForm.limit"
        :total="total"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      ></lb-page>
    </div>
    <el-dialog
      title="下载卡券码"
      :visible.sync="centerDialogVisible"
      width="400px"
      center
    >
      <div class="dialog-inner">
        <el-form @submit.native.prevent label-width="80px">
          <el-form-item label="员工">
            <el-select
              v-model="downloadForm.staff_id"
              @change="getRedQRQcode"
              placeholder="请选择"
            >
              <el-option
                v-for="item in staffArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <lb-image v-loading="imgLoading" :src="redSrc" v-if="redSrc"></lb-image>
        <lb-image
          v-loading="imgLoading"
          src="https://lbqny.migugu.com/admin/public/default.jpg"
          v-else
        ></lb-image>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">{{
          $t('action.cancel')
        }}</el-button>
        <el-button type="primary" @click="downloadRedPackit">下载</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      loading: false,
      imgLoading: false,
      ruleForm: {
        name: '',
        page: 1,
        limit: 10
      },
      centerDialogVisible: false,
      tableData: [],
      total: 0,
      staffArr: [],
      downloadForm: {
        id: '',
        staff_id: ''
      },
      redSrc: ''
    }
  },
  created () {
    this.getAllStaffList()
  },
  activated () {
    this.getTableDataList()
  },
  methods: {
    resetForm (name) {
      this.$refs[name].resetFields()
      this.getTableDataList(1)
    },
    handleSizeChange (val) {
      this.ruleForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.ruleForm.page = val
      this.getTableDataList()
    },
    /**
     * @method 确认是否删除
     */
    confirmDel (id) {
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.updateOrDelStatus(-1, id)
      }).catch(() => {

      })
    },

    /**
     * @method 温馨提示是否操作
     */
    confirmIsOperate (id) {
      this.$confirm('编辑该卡券后, 用户已领取该卡券信息不会发生变化!', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.$router.push(`/malls/addRedPackit?id=${id}`)
      }).catch(() => {

      })
    },

    /**
     * @method 获取卡券表格数据
     */
    getTableDataList (flag) {
      if (flag) this.ruleForm.page = 1
      this.loading = true
      let { ruleForm } = this
      this.$api.getRedPackitList(ruleForm).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.total = res.data.total
          this.tableData = res.data.data
        }
      })
    },

    /**
     * @method 修改状态
     */
    updateOrDelStatus (status, id) {
      this.$api.updateRedPackitStatus({ status, id }).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t(status === -1 ? 'tips.successDel' : 'tips.successOper'))
          if (status === -1) {
            this.ruleForm.page = this.ruleForm.page < Math.ceil((this.total - 1) / this.ruleForm.limit) ? this.ruleForm.page : Math.ceil((this.total - 1) / this.ruleForm.limit)
            this.getTableDataList()
          }
        }
      })
    },
    getAllStaffList () {
      this.$api.getAllStaffs({ limit: 100000 }).then(res => {
        this.staffArr = res.data.data
      })
    },
    getRedQRQcode () {
      this.imgLoading = true
      this.$api.downloadRedPackitCode(this.downloadForm).then(res => {
        this.imgLoading = false
        if (res.code === 200) {
          this.redSrc = res.data
        }
      })
    },
    downloadRedPackit () {
      if (!this.redSrc) {
        this.$message.error('没有卡券码可以下载！')
      } else {
        this.downloadImg(this.redSrc, '卡券码')
      }
    },
    /**
     * @method 下载图片
     */
    downloadImg (imgsrc, name) {
      this.$api.handleImgSrc(imgsrc).then(res => {
        let image = new Image()
        // 解决跨域 Canvas 污染问题
        image.setAttribute('crossOrigin', 'anonymous')
        image.onload = function () {
          let canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height
          let context = canvas.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)
          let url = canvas.toDataURL() // 得到图片的base64编码数据

          let a = document.createElement('a') // 生成一个a元素
          let event = new MouseEvent('click') // 创建一个单击事件
          a.download = name || 'photo' // 设置图片名称
          a.href = url // 将生成的URL设置为a.href属性
          a.dispatchEvent(event) // 触发a的单击事件
        }
        image.src = res
      })
    },
    openDialogRedPackit (id) {
      this.downloadForm.id = id
      this.downloadForm.staff_id = ''
      this.redSrc = ''
      this.centerDialogVisible = true
    }
  },
  watch: {
    $route: {
      deep: true,
      handler (val) {
        console.log(val)
        if (val.meta.refresh) {
          this.$route.meta.refresh = false
          this.getGoodsList()
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-red-packit {
  width: 100%;
  .el-input {
    width: 200px;
  }
  .dialog-inner {
    height: 300px;
    .el-image {
      width: 200px;
      height: 200px;
      margin: 0 auto;
    }
  }
}
</style>
